package com.leetcode.dataStruct.tree;

import com.leetcode.dataStruct.TreeNode;

import java.util.HashMap;
import java.util.Map;

public class PostInBuildTree {
    public static void main(String[] args) {

    }

    Map<Integer, Integer> indexMap = new HashMap<>();

    public TreeNode buildTree(int[] inorder, int[] postorder) {
        int n = inorder.length;
        for (int i = 0; i < n; i++) {
            indexMap.put(inorder[i], i);
        }
      return build(inorder, postorder,
                0, n - 1, 0, n - 1);
    }

    private TreeNode build(int[] inorder, int[] postorder,
                           int inorderLeft, int inorderRight,
                           int postLeft, int postRight) {
        if (postLeft > postRight || inorderLeft > inorderRight) {
            return null;
        }
        int inRoot = indexMap.get(postorder[postRight]);
        int leftTreeSize = inRoot - inorderLeft;
        TreeNode root = new TreeNode(postorder[postRight]);
        root.left = build(inorder, postorder, inorderLeft, inRoot - 1,
                postLeft, postLeft + leftTreeSize - 1);
        root.right = build(inorder, postorder, inRoot + 1, inorderRight,
                postLeft + leftTreeSize, postRight - 1);
        return root;
    }
}
